package com.gongpingjialoan.activity.main;

import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.gongpingjialoan.R;
import com.gongpingjialoan.api.ApiSecurity;
import com.gongpingjialoan.constant.Const;
import com.gongpingjialoan.data.UserManager;
import com.gongpingjialoan.global.GPJApplication;
import com.gongpingjialoan.network.NetDataJson;
import com.gongpingjialoan.receiver.SmsContentObserver;
import com.gongpingjialoan.utility.Utils;

import org.json.JSONObject;

/**
 * Created by Administrator on 2016/12/21.
 */
public class BindPhoneActivity extends BaseActivity implements View.OnClickListener {

    // 手机号 ， 密码 文本输入框
    private EditText ed_verifycode, ed_phone;

    private TextView mGetVerifycodeTv;

    private TextView sureTextView;

    private String phone = "";

    private boolean isPhoneLegal, isCodeLegal;

    private boolean isCountRunning = false;

    private SmsContentObserver mSmsContentObserver;

    private NetDataJson mNetDataJson;

    private UserManager mUserManager = null;

    private boolean isRefreshDiscountCar = true;

    private String loginType = "weixin";

    private String uri = "/mobile/account/wechat-register-bind-phone/";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.bind_phone_layout);
        setTitle("绑定手机号");
        isRefreshDiscountCar = getIntent().getBooleanExtra("isRefreshDiscountCar", true);
        loginType = getIntent().getStringExtra("login_type");
        if("weixin".equals(loginType)){
            uri = "/mobile/account/wechat-register-bind-phone/";
        }else if("xiaomi".equals(loginType)){
            uri = "/mobile/account/xiaomi-register-bind-phone/";
        }
        ed_phone = (EditText) findViewById(R.id.ed_phone);
        ed_verifycode = (EditText) findViewById(R.id.ed_verifycode);
        sureTextView = (TextView) findViewById(R.id.sure);
        mGetVerifycodeTv = (TextView) findViewById(R.id.get_verifycode_tv);
        mUserManager = new UserManager(this);
        sureTextView.setOnClickListener(this);
        mGetVerifycodeTv.setOnClickListener(this);
        mSmsContentObserver = new SmsContentObserver(this, smsHandler);
        initlistener();
    }

    private void initlistener() {
        ed_phone.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
                phone = ed_phone.getText().toString();
                if (ed_phone.getText().length() == 11) {
                    isPhoneLegal = true;
                    if (!isCountRunning) {
                        mGetVerifycodeTv.setEnabled(true);
                    }
                } else {
                    isPhoneLegal = false;
                    mGetVerifycodeTv.setEnabled(false);
                }
                getLoginLegal();
            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                                          int arg3) {
            }

            @Override
            public void afterTextChanged(Editable arg0) {
            }
        });



        ed_verifycode.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
                if (ed_verifycode.getText().length() == 6) {
                    isCodeLegal = true;
                } else {
                    isCodeLegal = false;
                }
                getLoginLegal();
            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                                          int arg3) {
            }

            @Override
            public void afterTextChanged(Editable arg0) {
            }
        });
    }

    private void getLoginLegal() {
        if (isPhoneLegal && isCodeLegal) {
            sureTextView.setEnabled(true);
        } else {
            sureTextView.setEnabled(false);
        }

    }

    private Handler smsHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                if (ed_verifycode != null) {
                    ed_verifycode.setText(msg.obj.toString());
                }
            }
        }
    };

    private void registerSmsContentObservers() {
        Uri smsUri = Uri.parse("content://sms");
        //smsContentObserver是SmsContentObserver的一个实例，可以在onCreate中初始化
        getContentResolver().registerContentObserver(smsUri, true, mSmsContentObserver);
    }

    private void unRegisterSmsContentObservers() {
        getContentResolver().unregisterContentObserver(mSmsContentObserver);
    }


    @Override
    public void onPause() {
        super.onPause();
        unRegisterSmsContentObservers();
    }

    @Override
    public void onResume() {
        super.onResume();
        registerSmsContentObservers();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mNetDataJson != null) {
            mNetDataJson.cancelTask();
            mNetDataJson = null;
        }
    }

    @Override
    public void onClick(View v) {
        if(v==mGetVerifycodeTv){
            getVergifyCode();
        }else if(v == sureTextView){
            String phone_num = ed_phone.getText().toString();
            String captcha = ed_verifycode.getText().toString();
            Utils.autoCloseKeyboard(this, sureTextView);
            showProgressDialog("登录中...");
            mUserManager.loginWithVerifyCode(phone_num, captcha, isRefreshDiscountCar, new UserManager.OnLoginResponse() {

                @Override
                public void onLoginError(String msg) {
                    hidenProgressDialog();
                    Toast.makeText(BindPhoneActivity.this, msg, Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onLoginSuccess(UserManager user) {
                    Toast.makeText(getApplicationContext(), "登录成功", Toast.LENGTH_SHORT).show();
                    hidenProgressDialog();
                    setResult(RESULT_OK);
                    BindPhoneActivity.this.finish();
                }
            } , uri);
        }
    }


    private void getVergifyCode() {
        mGetVerifycodeTv.setEnabled(false);
        isCountRunning = true;
        new CountDownTimer(Const.CODE_TIME * 1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                mGetVerifycodeTv.setText(millisUntilFinished / 1000 + "秒");
            }

            @Override
            public void onFinish() {
                isCountRunning = false;
                if (ed_phone.getText().length() == 11) {
                    mGetVerifycodeTv.setEnabled(true);
                }
                mGetVerifycodeTv.setText("重新发送");
            }
        }.start();
        if (mNetDataJson == null) {
            mNetDataJson = new NetDataJson(new NetDataJson.OnNetDataJsonListener() {

                @Override
                public void onDataJsonUpdate(JSONObject json) {
                    Toast.makeText(BindPhoneActivity.this, " 我们将给您来电告知验证码，请注意接听", Toast.LENGTH_SHORT).show();

                }

                @Override
                public void onDataJsonError(String errorMessage) {
                    Toast.makeText(BindPhoneActivity.this, errorMessage, Toast.LENGTH_SHORT).show();
                }
            });
        }
        String url = "/mobile/api/get-captcha/";
        mNetDataJson.addParam("phone", phone);
        mNetDataJson.addParam("device_code", GPJApplication.getInstance().getDeviceCode());
        mNetDataJson.addParam("sign", ApiSecurity.security(GPJApplication.getInstance().getSecert(),phone));
        mNetDataJson.setUrl(url);
        mNetDataJson.request("post");
    }
}
